package org.boulderfoodrescue.webapp.client.pickups.selectors;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasValue;

public class CustomSelectorDialog<T> extends DialogBox implements HasValue<T>{
	private T value;
	private CustomSelectorDialogView<T> view;
	
	public CustomSelectorDialog(SelectorInterface<T> selectorInterface, T donor){
		this(selectorInterface);	
		this.value = donor;
	}
	
	public CustomSelectorDialog(final SelectorInterface<T> selectorInterface){
		view = new CustomSelectorDialogView<T>(selectorInterface);
		view.addHandler(new CloseHandler<Boolean>(){
			@Override
			public void onClose(CloseEvent<Boolean> event) {
				if(event.getTarget())
					setValue(selectorInterface.getValue());
				hideDlg();
			}
		}, CloseEvent.getType());
		this.add(view);
	}
	
	private void hideDlg(){
		this.hide();
	}

	@Override
	public HandlerRegistration addValueChangeHandler(
			ValueChangeHandler<T> handler) {
		return null;
	}

	@Override
	public T getValue() {
		return value;
	}

	@Override
	public void setValue(T value) {
		this.value = value;
		ValueChangeEvent.fire(this, value);
	}

	@Override
	public void setValue(T value, boolean fireEvents) {
		this.value = value;
		if(fireEvents)
			ValueChangeEvent.fire(this, value);
		
	}

}
